<?php

namespace App\Miya\Models;

use App\Miya\Traits\Scope\OrderByIdTrait;
use Illuminate\Database\Eloquent\Model;

class Debris extends Model
{
    use OrderByIdTrait;

    protected $guarded = [];

    protected $casts = [
        'classifies' => 'json',
    ];

    public function getClassifiesAttribute($value)
    {
        return array_values(json_decode($value, true) ?: []);
    }

    public function getClassifiesWithDescendantsAttribute()
    {
        $classifies = $this->classifies;
        Classify::whereIn('id', $classifies)->with(['descendants'])
            ->get()->each(function ($classify) use (&$classifies) {
                $classifies = array_merge($classifies, $classify->descendants->pluck('id')->toArray());
            });

        return $classifies;
    }

    public function setClassifiesAttribute($value)
    {
        $this->attributes['classifies'] = json_encode(array_values($value));
    }

    public function module()
    {
        return $this->belongsTo(Module::class);
    }
}
